<template>
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>更新用户信息</span>
        </div>
        <el-form :model="userInfo" label-width="120px" :rules="rules" ref="userForm">
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="头像">
                <el-upload action="" :http-request="uploadFile" list-type="picture-card" limit="1" accept="image/*"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
                    :on-error="handleAvatarError" :file-list="fileList">

                    <el-icon>
                        <Plus />
                    </el-icon> </el-upload>
            </el-form-item>
            <el-form-item label="个人简介" prop="bio">
                <el-input type="textarea" v-model="userInfo.bio"></el-input>
            </el-form-item>
            <el-form-item label="班级" prop="className">
                <el-input v-model="userInfo.className"></el-input>
            </el-form-item>
            <el-form-item label="学校" prop="school">
                <el-input v-model="userInfo.school"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleUpdate">更新</el-button>
            </el-form-item>
        </el-form>
        <el-dialog v-model="dialogVisible" style="min-height: 600px;">
            <img style="width:100%" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { updateUserInfo, getUserDetails, uploadAvatar } from '@/service/user/userService';
import { ElNotification } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus'

interface UserInfo {
    email: string;
    avatar: string;
    bio: string;
    className: string;
    school: string;
}
const userId = localStorage.getItem("userId")

const userInfo = ref<UserInfo>({
    email: '',
    avatar: '',
    bio: '',
    className: '',
    school: ''
});

const fileList = ref<any[]>([]);
const userForm = ref();

const rules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
    ],
    bio: [
        { required: true, message: '请输入个人简介', trigger: 'blur' }
    ],
    className: [
        { required: true, message: '请输入班级', trigger: 'blur' }
    ],
    school: [
        { required: true, message: '请输入学校', trigger: 'blur' }
    ]
};

const fetchUserDetails = async () => {
    const details = await getUserDetails();
    if (details) {
        userInfo.value.email = details.email;
        userInfo.value.avatar = details.avatar;
        userInfo.value.bio = details.bio;
        userInfo.value.className = details.className;
        userInfo.value.school = details.school;
        fileList.value = details.avatar ? [{ name: 'Avatar', url: details.avatar }] : [];
    }
};

onMounted(() => {
    fetchUserDetails();
});
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 图片放大
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleUpdate = () => {
    userForm.value.validate(async (valid: boolean) => {
        if (valid) {
            try {
                const res = await updateUserInfo(userId, userInfo.value.email, userInfo.value.avatar, userInfo.value.bio, userInfo.value.className, userInfo.value.school);
                if (res.status == 200) {

                    ElNotification.success('用户信息更新成功');
                }
            } catch (error) {
                ElNotification.error('用户信息更新失败');
            }
        } else {
            ElNotification.error('请确保所有字段填写正确');
        }
    });
};
// 上传文件
const uploadFile = async (param: any) => {
    try {
        const response = await uploadAvatar(param.file, userId);
        if (response.status == 200) {
            userInfo.value.avatar = response.data;
            ElNotification.success(response.message);
        } else {
            userInfo.value.avatar = "";
            ElNotification.error(response.message);
        }
    } catch (error) {
        ElNotification.error('头像上传失败');
    }
};
const handleRemove = () => {
    userInfo.value.avatar = ""
}
const handleAvatarSuccess = () => {
    fileList.value = [{ name: 'Avatar', url: userInfo.value.avatar }];
};

const handleAvatarError = () => {
    ElNotification.error('头像上传失败');
};
</script>

<style scoped lang="less">
.box-card {
    width: 100%;
    min-height: 85vh;
    margin: 0 auto;
}

.el-upload {
    .el-upload-list__item {
        border-radius: 50%;
        overflow: hidden;
    }

    .el-icon-plus {
        font-size: 28px;
    }

    .el-upload__input {
        display: none;
    }
}
</style>
